<template>
  <div class="vulnerability-analysis-panel">
    <div v-if="!selectedVulnerability" class="vulnerability-selection">
      <h3>全球漏洞分析</h3>
      <div v-if="isLoading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="vulnerabilities.length === 0" class="empty-state">
        <el-empty description="暂无漏洞数据" />
      </div>
      <div v-else class="vulnerability-list">
        <el-table
          :data="vulnerabilities"
          stripe
          style="width: 100%"
          @row-click="handleVulnerabilitySelect"
        >
          <el-table-column prop="cve_id" label="CVE ID" min-width="120" />
          <el-table-column prop="title" label="漏洞名称" min-width="180" />
          <el-table-column prop="severity" label="严重程度" min-width="100">
            <template #default="scope">
              <el-tag :type="getSeverityType(scope?.row?.severity || '')">
                {{ scope?.row?.severity || '' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="affected_addresses" label="受影响地址数" min-width="120">
            <template #default="scope">
              {{ formatNumber(scope.row.affected_addresses) }}
            </template>
          </el-table-column>
          <el-table-column prop="affected_asns" label="受影响ASN数" min-width="120">
            <template #default="scope">
              {{ formatNumber(scope.row.affected_asns) }}
            </template>
          </el-table-column>
          <el-table-column prop="affected_countries" label="受影响国家数" min-width="120">
            <template #default="scope">
              {{ formatNumber(scope.row.affected_countries) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div v-else class="vulnerability-detail">
      <div class="detail-header">
        <el-button icon="ArrowLeft" @click="backToList">返回列表</el-button>
        <h3>{{ selectedVulnerability.cve_id }} 漏洞分析</h3>
      </div>

      <div class="vulnerability-overview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="CVE ID">{{ selectedVulnerability.cve_id }}</el-descriptions-item>
          <el-descriptions-item label="漏洞名称">{{ selectedVulnerability.title }}</el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag :type="getSeverityType(selectedVulnerability.severity)">
              {{ selectedVulnerability.severity }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="披露日期">{{ formatDate(selectedVulnerability.disclosure_date) }}</el-descriptions-item>
          <el-descriptions-item label="修复状态">
            <el-tag :type="selectedVulnerability.fix_available ? 'success' : 'danger'">
              {{ selectedVulnerability.fix_available ? '已修复' : '未修复' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="受影响地址数">{{ formatNumber(selectedVulnerability.affected_addresses) }}</el-descriptions-item>
          <el-descriptions-item label="全球占比" :span="2">
            <el-progress 
              :percentage="parseFloat(selectedVulnerability.affected_percentage || 0)" 
              :format="percentFormat"
              :color="getPercentageColor(selectedVulnerability.affected_percentage)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="漏洞描述" :span="2">
            {{ selectedVulnerability.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="tabs-container">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="ASN分布" name="asns">
            <div v-if="isLoadingAsns" class="loading-container">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="!vulnerabilityAsns.asns || vulnerabilityAsns.asns.length === 0" class="empty-state">
              <el-empty description="暂无ASN数据" />
            </div>
            <div v-else>
              <el-table
                :data="vulnerabilityAsns.asns"
                stripe
                style="width: 100%"
                @row-click="handleAsnSelect"
              >
                <el-table-column prop="asn" label="ASN" min-width="100" />
                <el-table-column prop="as_name" label="名称" min-width="180">
                  <template #default="scope">
                    {{ scope.row.as_name_zh || scope.row.as_name }}
                  </template>
                </el-table-column>
                <el-table-column prop="country_name" label="国家" min-width="100">
                  <template #default="scope">
                    {{ scope.row.country_name_zh || scope.row.country_name }}
                  </template>
                </el-table-column>
                <el-table-column prop="affected_addresses" label="受影响地址数" min-width="120">
                  <template #default="scope">
                    {{ formatNumber(scope.row.affected_addresses) }}
                  </template>
                </el-table-column>
                <el-table-column prop="affected_percentage" label="占比" min-width="150">
                  <template #default="scope">
                    <el-progress 
                      :percentage="parseFloat(scope.row.affected_percentage || 0)" 
                      :format="percentFormat"
                      :color="getPercentageColor(scope.row.affected_percentage)"
                    />
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="pagination">
                <el-pagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  :total="vulnerabilityAsns.total || 0"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="地区分布" name="regions">
            <div v-if="isLoadingRegions" class="loading-container">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="!vulnerabilityRegions || vulnerabilityRegions.length === 0" class="empty-state">
              <el-empty description="暂无地区数据" />
            </div>
            <div v-else class="region-distribution">
              <el-table
                :data="vulnerabilityRegions"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="region" label="地区" min-width="150" />
                <el-table-column prop="affected_addresses" label="受影响地址数" min-width="120">
                  <template #default="scope">
                    {{ formatNumber(scope.row.affected_addresses) }}
                  </template>
                </el-table-column>
                <el-table-column prop="total_addresses" label="地区总地址数" min-width="120">
                  <template #default="scope">
                    {{ formatNumber(scope.row.total_addresses) }}
                  </template>
                </el-table-column>
                <el-table-column prop="affected_percentage" label="占比" min-width="150">
                  <template #default="scope">
                    <el-progress 
                      :percentage="parseFloat(scope.row.affected_percentage || 0)" 
                      :format="percentFormat"
                      :color="getPercentageColor(scope.row.affected_percentage)"
                    />
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="chart-container" v-if="vulnerabilityRegions.length > 0">
                <h4>地区分布图</h4>
                <div ref="regionChartRef" style="width: 100%; height: 400px;"></div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 新增国家分布选项卡 -->
          <el-tab-pane label="国家分布" name="countries">
            <div v-if="isLoadingCountries" class="loading-container">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="!vulnerabilityCountries.countries || vulnerabilityCountries.countries.length === 0" class="empty-state">
              <el-empty description="暂无国家数据" />
            </div>
            <div v-else class="country-distribution">
              <el-table
                :data="vulnerabilityCountries.countries"
                stripe
                style="width: 100%"
                @row-click="handleCountrySelect"
              >
                <el-table-column prop="country_name" label="国家" min-width="150">
                  <template #default="scope">
                    {{ scope.row.country_name_zh || scope.row.country_name }}
                  </template>
                </el-table-column>
                <el-table-column prop="region" label="地区" min-width="120" />
                <el-table-column prop="affected_addresses" label="受影响地址数" min-width="120">
                  <template #default="scope">
                    {{ formatNumber(scope.row.affected_addresses) }}
                  </template>
                </el-table-column>
                <el-table-column prop="total_active_ipv6" label="国家总地址数" min-width="120">
                  <template #default="scope">
                    {{ formatNumber(scope.row.total_active_ipv6) }}
                  </template>
                </el-table-column>
                <el-table-column prop="affected_percentage" label="占比" min-width="150">
                  <template #default="scope">
                    <el-progress 
                      :percentage="parseFloat(scope.row.affected_percentage || 0)" 
                      :format="percentFormat"
                      :color="getPercentageColor(scope.row.affected_percentage)"
                    />
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="pagination">
                <el-pagination
                  v-model:current-page="countriesCurrentPage"
                  v-model:page-size="countriesPageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  :total="vulnerabilityCountries.total || 0"
                  @size-change="handleCountriesSizeChange"
                  @current-change="handleCountriesCurrentChange"
                />
              </div>
              
              <div class="chart-container" v-if="vulnerabilityCountries.countries && vulnerabilityCountries.countries.length > 0">
                <h4>国家分布图</h4>
                <div ref="countryChartRef" style="width: 100%; height: 400px;"></div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- ASN漏洞详情对话框 -->
    <el-dialog
      v-model="showAsnDetail"
      title="ASN漏洞详情"
      width="80%"
      destroy-on-close
    >
      <div v-if="!asnVulnerabilityDetail" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ASN">{{ asnVulnerabilityDetail.info.asn }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ asnVulnerabilityDetail.info.as_name_zh || asnVulnerabilityDetail.info.as_name }}</el-descriptions-item>
          <el-descriptions-item label="国家">{{ asnVulnerabilityDetail.info.country_name_zh || asnVulnerabilityDetail.info.country_name }}</el-descriptions-item>
          <el-descriptions-item label="漏洞">{{ asnVulnerabilityDetail.info.cve_id }}</el-descriptions-item>
          <el-descriptions-item label="受影响地址数">{{ formatNumber(asnVulnerabilityDetail.info.affected_addresses) }}</el-descriptions-item>
          <el-descriptions-item label="总地址数">{{ formatNumber(asnVulnerabilityDetail.info.total_active_ipv6) }}</el-descriptions-item>
          <el-descriptions-item label="占比" :span="2">
            <el-progress 
              :percentage="parseFloat(asnVulnerabilityDetail.info.affected_percentage || 0)" 
              :format="percentFormat"
              :color="getPercentageColor(asnVulnerabilityDetail.info.affected_percentage)"
            />
          </el-descriptions-item>
        </el-descriptions>

        <div class="chart-container" v-if="asnVulnerabilityDetail.prefixDistribution.length > 0">
          <h4>前缀分布</h4>
          <div ref="prefixChartRef" style="width: 100%; height: 400px;"></div>
        </div>

        <div class="prefix-table" v-if="asnVulnerabilityDetail.prefixDistribution.length > 0">
          <h4>前缀详情</h4>
          <el-table
            :data="asnVulnerabilityDetail.prefixDistribution"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="prefix" label="前缀" min-width="180">
              <template #default="scope">
                {{ scope.row.prefix }}/{{ scope.row.prefix_length }}
              </template>
            </el-table-column>
            <el-table-column prop="affected_addresses" label="受影响地址数" min-width="120">
              <template #default="scope">
                {{ formatNumber(scope.row.affected_addresses) }}
              </template>
            </el-table-column>
            <el-table-column prop="total_addresses" label="总地址数" min-width="120">
              <template #default="scope">
                {{ formatNumber(scope.row.total_addresses) }}
              </template>
            </el-table-column>
            <el-table-column prop="affected_percentage" label="占比" min-width="150">
              <template #default="scope">
                <el-progress 
                  :percentage="parseFloat(scope.row.affected_percentage || 0)" 
                  :format="percentFormat"
                  :color="getPercentageColor(scope.row.affected_percentage)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 国家漏洞详情对话框 -->
    <el-dialog
      v-model="showCountryDetail"
      title="国家漏洞详情"
      width="80%"
      destroy-on-close
    >
      <div v-if="!countryVulnerabilityDetail" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="国家">{{ countryVulnerabilityDetail.info.country_name_zh || countryVulnerabilityDetail.info.country_name }}</el-descriptions-item>
          <el-descriptions-item label="地区">{{ countryVulnerabilityDetail.info.region }}</el-descriptions-item>
          <el-descriptions-item label="漏洞">{{ countryVulnerabilityDetail.info.cve_id }}</el-descriptions-item>
          <el-descriptions-item label="受影响地址数">{{ formatNumber(countryVulnerabilityDetail.info.affected_addresses) }}</el-descriptions-item>
          <el-descriptions-item label="总地址数">{{ formatNumber(countryVulnerabilityDetail.info.total_active_ipv6) }}</el-descriptions-item>
          <el-descriptions-item label="占比" :span="2">
            <el-progress 
              :percentage="parseFloat(countryVulnerabilityDetail.info.affected_percentage || 0)" 
              :format="percentFormat"
              :color="getPercentageColor(countryVulnerabilityDetail.info.affected_percentage)"
            />
          </el-descriptions-item>
        </el-descriptions>


        <div class="asn-table" v-if="countryVulnerabilityDetail.asnDistribution.length > 0">
          <h4>ASN分布</h4>
          <el-table
            :data="countryVulnerabilityDetail.asnDistribution"
            stripe
            style="width: 100%"
            @row-click="handleCountryAsnSelect"
          >
            <el-table-column prop="asn" label="ASN" min-width="100" />
            <el-table-column prop="as_name" label="名称" min-width="180">
              <template #default="scope">
                {{ scope.row.as_name_zh || scope.row.as_name }}
              </template>
            </el-table-column>
            <el-table-column prop="affected_addresses" label="受影响地址数" min-width="120">
              <template #default="scope">
                {{ formatNumber(scope.row.affected_addresses) }}
              </template>
            </el-table-column>
            <el-table-column prop="total_active_ipv6" label="总地址数" min-width="120">
              <template #default="scope">
                {{ formatNumber(scope.row.total_active_ipv6) }}
              </template>
            </el-table-column>
            <el-table-column prop="affected_percentage" label="占比" min-width="150">
              <template #default="scope">
                <el-progress 
                  :percentage="parseFloat(scope.row.affected_percentage || 0)" 
                  :format="percentFormat"
                  :color="getPercentageColor(scope.row.affected_percentage)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="chart-container" v-if="countryVulnerabilityDetail.asnDistribution.length > 0">
          <h4>ASN分布图</h4>
          <div ref="countryAsnChartRef" style="width: 100%; height: 400px;"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick,  onUnmounted } from 'vue';
import { useDetectionStore } from '@/stores/detection';
import * as echarts from 'echarts/core';
import { PieChart, BarChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent, GridComponent, TitleComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { ElMessage } from 'element-plus'
// 注册ECharts组件
echarts.use([
  PieChart,
  BarChart,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  TitleComponent,
  CanvasRenderer
]);

const detectionStore = useDetectionStore();

// 状态变量
const isLoading = ref(false);
const isLoadingAsns = ref(false);
const isLoadingRegions = ref(false);
const isLoadingCountries = ref(false); // 新增国家加载状态
const isLoadingAsnDetail = ref(false); // 添加ASN详情加载状态
const isLoadingCountryDetail = ref(false); // 添加国家详情加载状态
const selectedVulnerability = ref(null);
const activeTab = ref('asns');
const currentPage = ref(1);
const pageSize = ref(20);
const countriesCurrentPage = ref(1); // 新增国家分页
const countriesPageSize = ref(20); // 新增国家分页大小
const showAsnDetail = ref(false);
const showCountryDetail = ref(false); // 新增国家详情对话框状态
const asnVulnerabilityDetail = ref(null);
const countryVulnerabilityDetail = ref(null); // 新增国家详情数据
const regionChartRef = ref(null);
const prefixChartRef = ref(null);
const countryChartRef = ref(null); // 新增国家图表引用
const countryAsnChartRef = ref(null); // 新增国家ASN图表引用
let regionChart = null;
let prefixChart = null;
let countryChart = null; // 新增国家图表实例
let countryAsnChart = null; // 新增国家ASN图表实例

// 计算属性
const vulnerabilities = computed(() => detectionStore.vulnerabilities || []);
const vulnerabilityAsns = computed(() => detectionStore.vulnerabilityAsns || { asns: [], total: 0 });
const vulnerabilityRegions = computed(() => {
  // 检查是否为对象且包含regions属性
  if (detectionStore.vulnerabilityRegions && typeof detectionStore.vulnerabilityRegions === 'object' && detectionStore.vulnerabilityRegions.regions) {
    return detectionStore.vulnerabilityRegions.regions;
  }
  // 如果是数组则直接返回，兼容旧数据结构
  if (Array.isArray(detectionStore.vulnerabilityRegions)) {
    return detectionStore.vulnerabilityRegions;
  }
  // 默认返回空数组
  return [];
});
const vulnerabilityCountries = computed(() => detectionStore.vulnerabilityCountries || { countries: [], total: 0 }); // 新增国家数据计算属性

// 生命周期钩子
onMounted(async () => {
  await fetchVulnerabilities();
});


// 监听标签页变化
watch(() => activeTab.value, async (newTab) => {
  console.log('漏洞分析面板标签页切换:', newTab);
  
  if (newTab === 'regions') {
    console.log('切换到地区选项卡');
    // 如果已经有数据，则在下一个渲染周期尝试渲染图表
    if (vulnerabilityRegions.value && vulnerabilityRegions.value.length > 0) {
      nextTick(() => {
        // 延迟一点时间确保DOM已经完全渲染
        setTimeout(() => {
          if (regionChartRef.value) {
            console.log('地区选项卡DOM已渲染，准备渲染图表');
            renderRegionChart();
          } else {
            console.warn('切换到地区选项卡，但DOM元素不存在');
          }
        }, 300);
      });
    } else if (selectedVulnerability.value) {
      // 如果没有数据但有选中的漏洞，则获取数据
      console.log('地区选项卡无数据，准备获取数据');
      await fetchVulnerabilityRegions();
      // 获取数据后尝试渲染图表
      nextTick(() => {
        setTimeout(() => {
          if (regionChartRef.value && vulnerabilityRegions.value && vulnerabilityRegions.value.length > 0) {
            renderRegionChart();
          }
        }, 300);
      });
    }
  }
  
  // 添加countries监听逻辑
  if (newTab === 'countries') {
    console.log('切换到国家选项卡');
    // 如果已经有数据，则在下一个渲染周期尝试渲染图表
    if (vulnerabilityCountries.value?.countries && vulnerabilityCountries.value.countries.length > 0) {
      nextTick(() => {
        // 延迟一点时间确保DOM已经完全渲染
        setTimeout(() => {
          if (countryChartRef.value) {
            console.log('国家选项卡DOM已渲染，准备渲染图表');
            renderCountryChart();
          } else {
            console.warn('切换到国家选项卡，但DOM元素不存在');
          }
        }, 300);
      });
    } else if (selectedVulnerability.value) {
      // 如果没有数据但有选中的漏洞，则获取数据
      console.log('国家选项卡无数据，准备获取数据');
      await fetchVulnerabilityCountries();
      // 获取数据后尝试渲染图表
      nextTick(() => {
        setTimeout(() => {
          if (countryChartRef.value && vulnerabilityCountries.value?.countries && vulnerabilityCountries.value.countries.length > 0) {
            renderCountryChart();
          }
        }, 300);
      });
    }
  }
});

// 监听漏洞ASN数据变化，更新图表
watch(vulnerabilityRegions, async () => {
  if (activeTab.value === 'regions' && vulnerabilityRegions.value.length > 0) {
    await nextTick();
    renderRegionChart();
  }
});

// 监听漏洞国家数据变化，更新图表
watch(vulnerabilityCountries, async () => {
  if (activeTab.value === 'countries' && vulnerabilityCountries.value.countries && vulnerabilityCountries.value.countries.length > 0) {
    await nextTick();
    renderCountryChart();
  }
});

// 监听ASN漏洞详情变化，更新图表
watch(asnVulnerabilityDetail, async () => {
  if (showAsnDetail.value && asnVulnerabilityDetail.value) {
    await nextTick();
    renderPrefixChart();
  }
});

// 监听国家漏洞详情变化，更新图表
watch(countryVulnerabilityDetail, async () => {
  if (showCountryDetail.value && countryVulnerabilityDetail.value) {
    await nextTick();
    renderCountryAsnChart();
  }
});

// 监听分页变化
watch([currentPage, pageSize], async () => {
  if (selectedVulnerability.value && activeTab.value === 'asns') {
    await fetchVulnerabilityAsns();
  }
});

// 监听国家分页变化
watch([countriesCurrentPage, countriesPageSize], async () => {
  if (selectedVulnerability.value && activeTab.value === 'countries') {
    await fetchVulnerabilityCountries();
  }
});

// 方法
async function fetchVulnerabilities() {
  isLoading.value = true;
  try {
    await detectionStore.fetchVulnerabilities();
  } catch (error) {
    console.error('获取漏洞列表失败:', error);
  } finally {
    isLoading.value = false;
  }
}

async function handleVulnerabilitySelect(row) {
  try {
    selectedVulnerability.value = row;
    
    // 确保漏洞ID存在
    if (!row || !row.vulnerability_id) {
      console.error('漏洞ID不存在');
      return;
    }
    // 获取漏洞详情
    const vulnerabilityDetail = await detectionStore.fetchVulnerabilityDetail(row.vulnerability_id);
    if (vulnerabilityDetail) {
      selectedVulnerability.value = {
        ...row,
        ...vulnerabilityDetail
      };
    } else {
      selectedVulnerability.value = row;
    }
    
    // 重置数据
    vulnerabilityAsns.value = { asns: [], total: 0 };
    vulnerabilityRegions.value = [];
    vulnerabilityCountries.value = { countries: [], total: 0 };
    
    // 重置分页
    currentPage.value = 1;
    pageSize.value = 10;
    countriesCurrentPage.value = 1;
    countriesPageSize.value = 10;
    
    // 设置默认标签页
    activeTab.value = 'asns';
    
    // 获取ASN数据
    await fetchVulnerabilityAsns();
  } catch (error) {
    console.error('选择漏洞失败:', error);
  }
}

// 添加缺失的 fetchVulnerabilityDetail 函数
async function fetchVulnerabilityDetail(vulnerabilityId) {
  if (!vulnerabilityId) {
    console.error('vulnerabilityId 未定义，无法获取漏洞详情');
    return;
  }
  
  try {
    isLoading.value = true;
    await detectionStore.fetchVulnerabilityDetail(vulnerabilityId);
    selectedVulnerability.value = detectionStore.selectedVulnerability;
  } catch (err) {
    console.error('获取漏洞详情失败:', err);
    throw err;
  } finally {
    isLoading.value = false;
  }
}


async function fetchVulnerabilityAsns() {
  if (!selectedVulnerability.value || !selectedVulnerability.value.vulnerability_id) {
    console.error('获取漏洞ASN列表失败: 漏洞ID为undefined');
    return;
  }
  
  try {
    isLoadingAsns.value = true;
    await detectionStore.fetchVulnerabilityAsns(
      selectedVulnerability.value.vulnerability_id,
      pageSize.value,
      (currentPage.value - 1) * pageSize.value
    );
    // 不要直接修改计算属性，store 中的数据更新后，计算属性会自动更新
  } catch (error) {
    console.error('获取漏洞ASN列表失败:', error);
  } finally {
    isLoadingAsns.value = false;
  }
}


async function fetchVulnerabilityRegions() {
  if (!selectedVulnerability.value || !selectedVulnerability.value.vulnerability_id) {
    console.error('获取漏洞地区分布失败: 漏洞ID为undefined');
    return;
  }
  
  isLoadingRegions.value = true;
  try {
    await detectionStore.fetchVulnerabilityRegions(
      selectedVulnerability.value.vulnerability_id
    );
    
    // 在下一个渲染周期后初始化图表，但不立即渲染
    // 只有当activeTab为regions时才渲染
    if (activeTab.value === 'regions') {
      nextTick(() => {
        // 延迟一点时间确保DOM已经完全渲染
        setTimeout(() => {
          if (regionChartRef.value && 
              vulnerabilityRegions.value && 
              vulnerabilityRegions.value.length > 0) {
            console.log('尝试渲染地区图表', {
              hasRef: !!regionChartRef.value,
              refElement: regionChartRef.value,
              dataLength: vulnerabilityRegions.value.length
            });
            renderRegionChart();
          } else {
            console.log('不满足渲染地区图表的条件，跳过渲染', {
              hasRef: !!regionChartRef.value,
              hasData: !!vulnerabilityRegions.value,
              dataLength: vulnerabilityRegions.value ? vulnerabilityRegions.value.length : 0
            });
          }
        }, 300); // 给DOM渲染一些时间
      });
    }
  } catch (error) {
    console.error('获取漏洞地区分布失败:', error);
  } finally {
    isLoadingRegions.value = false;
  }
}

async function fetchVulnerabilityCountries() {
  if (!selectedVulnerability.value) {
    console.error('selectedVulnerability 未定义，无法获取国家列表');
    return;
  }
  
  try {
    isLoadingCountries.value = true;
    console.log('开始获取漏洞国家列表', {
      vulnerabilityId: selectedVulnerability.value.vulnerability_id,
      pageSize: countriesPageSize.value,
      offset: (countriesCurrentPage.value - 1) * countriesPageSize.value,
      activeTab: activeTab.value
    });
    
    await detectionStore.fetchVulnerabilityCountries(
      selectedVulnerability.value.vulnerability_id,
      countriesPageSize.value,
      (countriesCurrentPage.value - 1) * countriesPageSize.value
    );
    
    console.log('获取漏洞国家列表成功', {
      hasData: !!detectionStore.vulnerabilityCountries?.countries,
      dataLength: detectionStore.vulnerabilityCountries?.countries?.length || 0,
      activeTab: activeTab.value
    });
    
    // 确保当前标签页是国家分布，并且数据已加载
    if (activeTab.value === 'countries' && detectionStore.vulnerabilityCountries?.countries?.length > 0) {
      // 使用nextTick和setTimeout确保DOM已更新
      nextTick(() => {
        setTimeout(() => {
          if (countryChartRef.value) {
            console.log('DOM已更新，准备渲染国家图表');
            renderCountryChart();
          } else {
            console.warn('获取数据后，国家图表DOM元素仍不存在');
          }
        }, 300);
      });
    }
  } catch (err) {
    console.error('获取漏洞国家列表失败:', err);
    ElMessage.error('获取漏洞国家列表失败: ' + err.message);
  } finally {
    isLoadingCountries.value = false;
  }
}

function backToList() {
  selectedVulnerability.value = null;
  activeTab.value = 'asns';
  currentPage.value = 1;
  countriesCurrentPage.value = 1;
}

function handleSizeChange(size) {
  pageSize.value = size;
  currentPage.value = 1;
}

function handleCurrentChange(page) {
  currentPage.value = page;
}

function handleCountriesSizeChange(size) {
  countriesPageSize.value = size;
  countriesCurrentPage.value = 1;
}

function handleCountriesCurrentChange(page) {
  countriesCurrentPage.value = page;
}

async function handleAsnSelect(row) {
  try {
    isLoadingAsnDetail.value = true;
    showAsnDetail.value = true;
    
    const detail = await detectionStore.fetchAsnVulnerabilityDetail(
      row.asn,
      selectedVulnerability.value.vulnerability_id
    );
    
    if (detail) {
      asnVulnerabilityDetail.value = detail;
    }
    
    // 在下一个渲染周期后初始化图表
    nextTick(() => {
      if (asnVulnerabilityDetail.value && 
          asnVulnerabilityDetail.value.prefixDistribution && 
          asnVulnerabilityDetail.value.prefixDistribution.length > 0) {
        renderPrefixChart();
      }
    });
  } catch (error) {
    console.error('获取ASN漏洞详情失败:', error);
    ElMessage.error('获取ASN漏洞详情失败');
  } finally {
    isLoadingAsnDetail.value = false;
  }
}

async function handleCountrySelect(row) {
  try {
    isLoadingCountryDetail.value = true;
    showCountryDetail.value = true;
    
    const response = await detectionStore.fetchCountryVulnerabilityDetail(
      row.country_id,
      selectedVulnerability.value.vulnerability_id
    );
    
    countryVulnerabilityDetail.value = response;
    
    // 在下一个渲染周期后初始化图表
    nextTick(() => {
      if (countryVulnerabilityDetail.value && 
          countryVulnerabilityDetail.value.asnDistribution && 
          countryVulnerabilityDetail.value.asnDistribution.length > 0) {
        renderCountryAsnChart();
      }
    });
  } catch (error) {
    console.error('获取国家漏洞详情失败:', error);
    ElMessage.error('获取国家漏洞详情失败');
  } finally {
    isLoadingCountryDetail.value = false;
  }
}

async function handleCountryAsnSelect(row) {
  try {
    asnVulnerabilityDetail.value = null;
    showAsnDetail.value = true;
    
    const detail = await detectionStore.fetchAsnVulnerabilityDetail(
      row.asn,
      selectedVulnerability.value.vulnerability_id
    );
    
    if (detail) {
      asnVulnerabilityDetail.value = detail;
    }
  } catch (error) {
    console.error('获取ASN漏洞详情失败:', error);
  }
}

function renderRegionChart() {
  try {
    // 确保DOM元素存在
    if (!regionChartRef.value) {
      console.warn('地区图表DOM元素不存在，无法渲染图表');
      return;
    }
    
    // 确保数据存在
    if (!vulnerabilityRegions.value || !Array.isArray(vulnerabilityRegions.value) || vulnerabilityRegions.value.length === 0) {
      console.warn('地区数据不存在或为空，无法渲染图表');
      return;
    }
    
    // 确保DOM元素已挂载到文档中
    if (!document.body.contains(regionChartRef.value)) {
      console.warn('地区图表DOM元素未挂载到文档中，无法渲染图表');
      return;
    }
    
    console.log('开始渲染地区图表', {
      element: regionChartRef.value,
      data: vulnerabilityRegions.value
    });
    
    // 如果已有实例，先销毁
    if (regionChart) {
      regionChart.dispose();
      regionChart = null;
    }
    
    // 初始化图表
    regionChart = echarts.init(regionChartRef.value);
    
    // 准备数据
    const data = vulnerabilityRegions.value.map(item => ({
      name: item.region || '未知地区',
      value: parseInt(item.affected_addresses) || 0
    }));
    
    // 设置图表选项
    const option = {
      title: {
        text: '漏洞地区分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: data.map(item => item.name)
      },
      series: [
        {
          name: '受影响地址数',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data
        }
      ]
    };
    
    // 应用选项
    regionChart.setOption(option);
    console.log('地区图表渲染成功');
  } catch (error) {
    console.error('渲染地区图表时发生错误:', error);
  }
}


function renderCountryChart() {
  try {
    console.log('尝试渲染国家图表', {
      hasRef: !!countryChartRef.value,
      refElement: countryChartRef.value,
      hasData: !!vulnerabilityCountries.value?.countries,
      dataLength: vulnerabilityCountries.value?.countries?.length || 0,
      activeTab: activeTab.value,
      domExists: countryChartRef.value ? document.body.contains(countryChartRef.value) : false,
      domId: countryChartRef.value ? countryChartRef.value.id : 'undefined',
      domVisible: countryChartRef.value ? window.getComputedStyle(countryChartRef.value).display !== 'none' : false
    });
    
    // 确保DOM元素存在
    if (!countryChartRef.value) {
      console.warn('国家图表DOM元素不存在，无法渲染图表');
      return;
    }
    
    // 确保数据存在
    if (!vulnerabilityCountries.value?.countries || !Array.isArray(vulnerabilityCountries.value.countries) || vulnerabilityCountries.value.countries.length === 0) {
      console.warn('国家数据不存在或为空，无法渲染图表');
      return;
    }
    
    // 确保DOM元素已挂载到文档中
    if (!document.body.contains(countryChartRef.value)) {
      console.warn('国家图表DOM元素未挂载到文档中，无法渲染图表');
      return;
    }
    
    // 确保DOM元素可见
    if (window.getComputedStyle(countryChartRef.value).display === 'none') {
      console.warn('国家图表DOM元素不可见，可能导致渲染问题');
      // 继续尝试渲染，但记录警告
    }
    
    console.log('开始渲染国家图表', {
      element: countryChartRef.value,
      data: vulnerabilityCountries.value.countries
    });
    
    // 如果已有实例，先销毁
    if (countryChart) {
      countryChart.dispose();
      countryChart = null;
    }
    
    // 初始化图表
    countryChart = echarts.init(countryChartRef.value);
    
    // 准备数据
    const data = vulnerabilityCountries.value.countries.map(item => ({
      name: item.country_name_zh || item.country_name || '未知国家',
      value: parseInt(item.affected_addresses) || 0
    }));
    
    // 设置图表选项
    const option = {
      title: {
        text: '漏洞国家分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: data.map(item => item.name)
      },
      series: [
        {
          name: '受影响地址数',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data
        }
      ]
    };
    
    // 应用选项
    countryChart.setOption(option);
    console.log('国家图表渲染成功');
  } catch (error) {
    console.error('渲染国家图表时发生错误:', error);
    ElMessage.error('渲染国家图表失败: ' + error.message);
  }
}


function renderPrefixChart() {
  if (!prefixChartRef.value || !asnVulnerabilityDetail.value) return;
  
  if (prefixChart) {
    prefixChart.dispose();
  }
  
  prefixChart = echarts.init(prefixChartRef.value);
  
  const prefixData = asnVulnerabilityDetail.value.prefixDistribution.map(item => {
    // 确保affected_percentage是数字
    const percentage = typeof item.affected_percentage === 'number' 
      ? item.affected_percentage 
      : parseFloat(item.affected_percentage || 0);
    
    return {
      name: `${item.prefix}/${item.prefix_length}`,
      value: item.affected_addresses,
      percentage: isNaN(percentage) ? 0 : percentage.toFixed(2) // 添加检查确保是数字
    };
  });
  
  const option = {
    title: {
      text: 'ASN前缀漏洞分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 地址 ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: prefixData.map(item => item.name)
    },
    series: [
      {
        name: '受影响地址数',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: prefixData
      }
    ]
  };
  
  prefixChart.setOption(option);
  
  window.addEventListener('resize', () => {
    prefixChart && prefixChart.resize();
  });
}

function renderCountryAsnChart() {
  if (!countryAsnChartRef.value || !countryVulnerabilityDetail.value) return;
  
  if (countryAsnChart) {
    countryAsnChart.dispose();
  }
  
  countryAsnChart = echarts.init(countryAsnChartRef.value);
  
  const asnData = countryVulnerabilityDetail.value.asnDistribution.map(item => ({
    name: `${item.asn} (${item.as_name_zh || item.as_name})`,
    value: item.affected_addresses
  }));
  
  const option = {
    title: {
      text: '国家ASN漏洞分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 地址 ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: asnData.map(item => item.name)
    },
    series: [
      {
        name: '受影响地址数',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: asnData
      }
    ]
  };
  
  countryAsnChart.setOption(option);
  
  window.addEventListener('resize', () => {
    countryAsnChart && countryAsnChart.resize();
  });
}

// 工具函数
function formatNumber(num) {
  if (num === undefined || num === null) return '0';
  return new Intl.NumberFormat().format(num);
}

function formatDate(dateStr) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString();
}

function percentFormat(percentage) {
  return percentage.toFixed(2) + '%';
}

function getPercentageColor(percentage) {
  if (percentage >= 50) return '#F56C6C';
  if (percentage >= 20) return '#E6A23C';
  return '#67C23A';
}

function getSeverityType(severity) {
  if (!severity) return 'default'; // 添加空值检查
  
  switch(severity.toUpperCase()) {
    case 'CRITICAL':
      return 'error';
    case 'HIGH':
      return 'warning';
    case 'MEDIUM':
      return 'info';
    case 'LOW':
      return 'success';
    default:
      return 'default';
  }
}

// 确保在组件卸载时清理图表实例和事件监听器
onUnmounted(() => {
  // 清理所有图表实例
  if (regionChart) {
    regionChart.dispose();
    regionChart = null;
  }
  
  if (prefixChart) {
    prefixChart.dispose();
    prefixChart = null;
  }
  
  if (countryChart) {
    countryChart.dispose();
    countryChart = null;
  }
  
  if (countryAsnChart) {
    countryAsnChart.dispose();
    countryAsnChart = null;
  }
  
  // 移除可能的事件监听器
  window.removeEventListener('resize', handleResize);
});

function handleResize() {
  if (regionChart && regionChartRef.value) {
    regionChart.resize();
  }
  if (prefixChart && prefixChartRef.value) {
    prefixChart.resize();
  }
  if (countryChart && countryChartRef.value) {
    countryChart.resize();
  }
  if (countryAsnChart && countryAsnChartRef.value) {
    countryAsnChart.resize();
  }
}

watch(activeTab, (newTab) => {
  // 保留原有的regions监听逻辑
  if (newTab === 'regions') {
    // 如果已经有数据，则在下一个渲染周期尝试渲染图表
    if (vulnerabilityRegions.value && vulnerabilityRegions.value.length > 0) {
      nextTick(() => {
        // 延迟一点时间确保DOM已经完全渲染
        setTimeout(() => {
          if (regionChartRef.value) {
            renderRegionChart();
          } else {
            console.warn('切换到地区选项卡，但DOM元素不存在');
          }
        }, 300);
      });
    } else if (selectedVulnerability.value) {
      // 如果没有数据但有选中的漏洞，则获取数据
      fetchVulnerabilityRegions();
    }
  }
  
  // 添加countries监听逻辑
  if (newTab === 'countries') {
    console.log('切换到国家选项卡');
    // 如果已经有数据，则在下一个渲染周期尝试渲染图表
    if (vulnerabilityCountries.value?.countries && vulnerabilityCountries.value.countries.length > 0) {
      nextTick(() => {
        // 延迟一点时间确保DOM已经完全渲染
        setTimeout(() => {
          if (countryChartRef.value) {
            console.log('国家选项卡DOM已渲染，准备渲染图表');
            renderCountryChart();
          } else {
            console.warn('切换到国家选项卡，但DOM元素不存在');
          }
        }, 300);
      });
    } else if (selectedVulnerability.value) {
      // 如果没有数据但有选中的漏洞，则获取数据
      console.log('国家选项卡无数据，准备获取数据');
      fetchVulnerabilityCountries();
    }
  }
});
</script>

<style scoped>
.vulnerability-analysis-panel {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}


.vulnerability-selection,
.vulnerability-detail,
.vulnerability-overview,
.tabs-container,
.region-distribution,
.country-distribution,
.chart-container {
  background-color: #ffffff;
}


.vulnerability-selection h3,
.vulnerability-detail h3 {
  margin-bottom: 20px;
  text-align: center;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0 0 0 20px;
}

.vulnerability-overview {
  margin-bottom: 30px;
}

.tabs-container {
  margin-top: 20px;
}

.loading-container,
.empty-state {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.chart-container {
  margin-top: 30px;
}

.chart-container h4 {
  text-align: center;
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.prefix-table,
.asn-table {
  margin-top: 30px;
}

.prefix-table h4,
.asn-table h4 {
  margin-bottom: 15px;
}
</style>